<template>
    <div class="app-container">
        <el-row :gutter="20" class="div-height-left">
            <el-col v-if="userInfo.userId === '1'" :span="4" class="div-height-left">
                <sys-org-tree @treeClick="treeClick" />
            </el-col>
            <el-col :span="userInfo.userId === '1' ? 20 : 24" :xs="24">
                <div class="search-container">
                    <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams"
                        label-width="120px">
                        <el-form-item label="科室分组名称" prop="deptGroupName">
                            <el-input v-model="queryParams.deptGroupName" clearable placeholder="请输入科室分组名称"
                                @keyup.enter.native="handleQuery" />
                        </el-form-item>
                        <div style="float: right" class="mr20">
                            <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery" />
                        </div>
                    </el-form>
                </div>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button v-hasPerm="['system:deptGroup:add']" plain type="primary"
                            @click="handleAdd"><template #icon><i-ep-plus /></template>新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPerm="['system:deptGroup:edit']" :disabled="single" plain type="success"
                            @click="handleUpdate"><template #icon><i-ep-edit /></template>修改
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPerm="['system:deptGroup:remove']" :disabled="multiple" plain type="danger"
                            @click="handleDelete"><template #icon><i-ep-delete /></template>删除
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPerm="['system:deptGroup:export']" plain type="warning"
                            @click="handleExport"><template #icon><i-ep-download /></template>导出
                        </el-button>
                    </el-col>
                </el-row>

                <el-table v-adaptive :data="deptGroupList" :border="true" stripe highlight-current-row
                    @selection-change="handleSelectionChange" :header-cell-style="$headerCellStyle">
                    <el-table-column :align="'center'" type="selection" width="55" />
                    <!--                    <el-table-column label="科室分组" :align="'center'" prop="deptGroupId" v-if="true"/>-->
                    <el-table-column :align="'left'" label="科室分组名称" prop="deptGroupName" />
                    <el-table-column :align="'center'" label="机构id" prop="orgId" />
                    <el-table-column :align="'center'" label="显示顺序" prop="orderNum" />
                    <el-table-column :align="'center'" label="备注" prop="remark" />
                    <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作">
                        <template #default="scope">
                            <el-button v-hasPerm="['system:deptGroup:edit']" type="success"
                                @click="handleUpdate(scope.row)"><template #icon><i-ep-edit /></template>分配科室
                            </el-button>
                            <el-button v-hasPerm="['system:deptGroup:edit']" type="primary"
                                @click="handleAuthUser(scope.row)"><template #icon><i-ep-user /></template>分配人员
                            </el-button>
                            <el-button v-hasPerm="['system:deptGroup:remove']" type="danger"
                                @click="handleDelete(scope.row)"><template #icon><i-ep-delete /></template>删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList" />
            </el-col>
        </el-row>
        <!-- 添加或修改科室分组对话框 -->
        <el-dialog :close-on-click-modal="false" :title="title" v-model="open" append-to-body width="40%">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-row :gutter="40" class="div-height-left">
                    <el-col :span="12">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="科室分组名称" prop="deptGroupName">
                                    <el-input v-model="form.deptGroupName" placeholder="请输入科室分组名称" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="显示顺序" prop="orderNum">
                                    <el-input v-model="form.orderNum" placeholder="请输入显示顺序" type="number" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="form.remark" :autosize="{ minRows: 4, maxRows: 8 }"
                                        placeholder="请输入内容" type="textarea" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="12" class="div-height-left">
                        <dept-tree ref="deptTreeRef" :show-checkbox="true" :default-checked-keys="defaultCheckedKeys"
                            :org-id="queryParams.orgId" />
                    </el-col>
                </el-row>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {addDeptGroup, delDeptGroup, getDeptGroup, selectPageDeptGroup, updateDeptGroup} from "@/api/system/deptGroup";
import {useUserStoreHook} from "@/store/modules/user";
import {useRouter} from "vue-router";
// import deptTree from "@/components/Dept/deptTree.vue"

const useUserStore = useUserStoreHook();
const router = useRouter()
const deptTreeRef = ref()
const formRef = ref()
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
// 按钮loading
const buttonLoading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 科室分组表格数据
const deptGroupList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    deptGroupName: undefined,
    orgId: undefined,
    orderNum: undefined,
})
// 表单参数
const form = ref<any>({})
// 已选中的科室树节点
const defaultCheckedKeys = ref([])
const deptTreeKey = ref(new Date().getTime())
// 表单校验
const rules = ref({
    deptGroupId: [
        { required: true, message: "科室分组不能为空", trigger: "blur" }
    ],
    deptGroupName: [
        { required: true, message: "科室分组名称不能为空", trigger: "blur" }
    ],
    orderNum: [
        { required: true, message: "显示顺序不能为空", trigger: "blur" }
    ],
})
if (userInfo.orgId) {
    queryParams.value.orgId = userInfo.orgId
    getList()
}
/** 左侧科室树节点点击事件 */
function treeClick(obj) {
    queryParams.value.orgId = obj.id
    getList()
}
/** 查询科室分组列表 */
function getList() {
    if (!queryParams.value.orgId) {
        return ElMessage.error("请先选择左侧所属机构后查询")
    }
    selectPageDeptGroup(queryParams.value).then((response: any) => {
        deptGroupList.value = response.rows;
        total.value = response.total;
    });
}
// 取消按钮
function cancel() {
    defaultCheckedKeys.value = []
    open.value = false;
    reset();
}
// 表单重置
function reset() {
    form.value = {
        deptGroupId: undefined,
        deptGroupName: undefined,
        orderNum: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        orgId: queryParams.value.orgId
    };
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    queryParamsRef.value.resetFields()
    handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.deptGroupId)
    single.value = selection.length !== 1
    multiple.value = !selection.length
}/** 新增按钮操作 */
function handleAdd() {
    if (!userInfo.orgId && !queryParams.value.orgId) {
        return ElMessage.error("请先选择左侧所属机构后查询")
    }
    defaultCheckedKeys.value = []
    deptTreeKey.value = new Date().getTime()
    reset();
    open.value = true;
    title.value = "添加科室分组";
}
/** 分配按钮操作 */
function handleUpdate(row) {
    if (!userInfo.orgId && !queryParams.value.orgId) {
        return ElMessage.error("请先选择左侧所属机构后查询")
    }
    reset();
    open.value = true;
    const deptGroupId = row.deptGroupId || ids.value
    getDeptGroup(deptGroupId).then(response => {
        deptTreeRef.value.clearTheSelection()
        let data = response.data;
        form.value = data;
        defaultCheckedKeys.value = data.deptIds
        // this.deptTreeKey = new Date().getTime()
        title.value = "修改科室分组";
    });
}
/** 分配用户操作 */
function handleAuthUser(row) {
    const deptGroupId = row.deptGroupId;
    const businessType = '2';
    router.push("/system/role-auth/user/" + queryParams.value.orgId + "/" + deptGroupId + "/" + businessType);
}
/** 提交按钮 */
function submitForm() {
    (formRef.value as any).validate(valid => {
        if (valid) {
            buttonLoading.value = true;
            form.value.deptIds = deptTreeRef.value.getCheckedKeys()
            if (form.value.deptGroupId != null) {
                updateDeptGroup(form.value).then(_response => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            } else {
                addDeptGroup(form.value).then(_response => {
                    ElMessage.success("新增成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            }
        }
    });
}
// 检测orgId是否存在
// checkOrgIdExist () {
//     if (!this.userInfo.orgId && !this.queryParams.orgId) {
//         return ElMessage.error("请先选择左侧所属机构后查询")
//     }
// },




/** 删除按钮操作 */
function handleDelete(row) {
    const deptGroupIds = row.deptGroupId || ids.value;
    ElMessageBox.confirm('分组可能存在【科室和用户对照信息】，如果删除的话，将会同时删除【科室和用户的信息对照】，是否确认删除？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        delDeptGroup(deptGroupIds).then(() => {
            getList();
            ElMessage.success("删除成功");
        })
    }).catch(() => {
    })
}
/** 导出按钮操作 */
function handleExport() {
    // this.download('system/deptGroup/export', {
    //     ...this.queryParams
    // }, `deptGroup_${new Date().getTime()}.xlsx`)
}
</script>
<script lang="ts">
export default {
    name: "DeptGroup"
}
</script>

<style scoped>
:deep(.el-dialog) {
    height: calc(100% - 300px)
}

:deep(.el-dialog__body) {
    height: calc(100% - 100px);
    overflow-y: auto;
}
</style>
